package com.zahb.qadx.ui.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewbinding.ViewBinding;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.base.BaseFragmentV2;
import com.zahb.qadx.databinding.FragmentExaminationListBinding;
import com.zahb.qadx.model.Curriculum;
import com.zahb.qadx.model.TaskListBean;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.skeleton.RecyclerViewSkeletonScreen;
import com.zahb.qadx.skeleton.Skeleton;
import com.zahb.qadx.ui.activity.CurriculumDetailsActivity;
import com.zahb.qadx.ui.activity.topic.TheTestActivity;
import com.zahb.qadx.util.CompatHelper;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.DisplayUtil;
import com.zahb.qadx.util.ImageLoaderKt;
import com.zahb.qadx.util.WebViewHelper;
import com.zahb.qadx.webview.MyWebViewActivity;

import org.jetbrains.annotations.NotNull;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by Zdw on 2020/11/13 15:51
 */
public class TaskListFragment extends BaseFragmentV2 implements OnRefreshLoadMoreListener, OnItemClickListener {

    RecyclerView mRecyclerView;
    SmartRefreshLayout mRefreshLayout;

    private boolean mHasClickToNewPage = false;// 记录点击跳转新页面
    private boolean mIsFirstLoad = true;// 是否第一次，处理懒加载
    private int mPage;
    private static final int PAGE_SIZE = 10;
    private int mType = -1;// 1待完成 2已完成 3已过期

    private TaskAdapter mTaskAdapter;

    private RecyclerViewSkeletonScreen mSkeletonScreen;
    private long mSkeletonShowTime;

    private TaskListFragment() {
    }

    public static TaskListFragment newInstance(int type) {
        Bundle args = new Bundle();
        args.putInt("type", type);
        TaskListFragment fragment = new TaskListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mType = mArguments.getInt("type", -1);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mIsFirstLoad) {
            mIsFirstLoad = false;
            //mRefreshLayout.autoRefresh();
            onRefresh(mRefreshLayout);
            showSkeleton();
        }

        if (mHasClickToNewPage) {
            mHasClickToNewPage = false;
            mRefreshLayout.autoRefresh();
        }
    }

    @org.jetbrains.annotations.Nullable
    @Override
    public ViewBinding initViewBinding(@NotNull LayoutInflater inflater, @org.jetbrains.annotations.Nullable ViewGroup container) {
        FragmentExaminationListBinding binding = FragmentExaminationListBinding
                .inflate(inflater, container, false);
        mRefreshLayout = binding.refreshLayout;
        mRecyclerView = binding.recyclerView;
        return binding;
    }

    @Override
    protected void initViews(View rootView) {
        mRefreshLayout.setOnRefreshLoadMoreListener(this);
        mRefreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mTaskAdapter = new TaskAdapter(R.layout.item_list_task);
        View emptyView = View.inflate(getContext(), R.layout.empty_layout, null);
        emptyView.setVisibility(View.VISIBLE);
        mTaskAdapter.setEmptyView(emptyView);
        mTaskAdapter.setUseEmpty(true);
        mRecyclerView.setAdapter(mTaskAdapter);
        mTaskAdapter.setOnItemClickListener(this);
        int divider = DisplayUtil.dip2px(10f);
        mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                if (parent.getAdapter() == null) return;
                outRect.set(0, 0, 0, divider);
            }
        });
    }

    private void showSkeleton() {
        mRefreshLayout.setEnableRefresh(false);
        mSkeletonScreen = Skeleton.bind(mRecyclerView)
                .adapter(mTaskAdapter)
                .shimmer(true)
                .shimmerMode(RecyclerViewSkeletonScreen.SHIMMER_MODE_ITEM_CHILD)
                .angle(15)
                .frozen(true)
                //.color(R.color.black_333333)
                .duration(1000)
                .count(10)
                .load(R.layout.item_list_task_skeleton)
                .show();
        mSkeletonShowTime = System.currentTimeMillis();
    }

    private void hideSkeleton() {
        if (mSkeletonScreen != null) {
            long currentTime = System.currentTimeMillis();
            if (currentTime - mSkeletonShowTime > Constant.MIN_NETWORK_TIME) {
                mRefreshLayout.setEnableRefresh(true);
                mSkeletonScreen.hide();
                mSkeletonScreen = null;
            } else {
                addDisposable(Observable.timer(mSkeletonShowTime + Constant.MIN_NETWORK_TIME - currentTime, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aLong -> hideSkeleton()));
            }
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        mPage++;
        getTaskList();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mPage = 1;
        getTaskList();
    }

    private void getTaskList() {
        addDisposable(RetrofitService.getNetService()
                .getTaskList(mPage, PAGE_SIZE, mType)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (mPage == 1) {
                        mRefreshLayout.finishRefresh();
                    } else {
                        mRefreshLayout.finishLoadMore(1000);
                    }
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        List<TaskListBean> taskList = response.getData().getList();
                        if (mPage == 1) {
                            mTaskAdapter.setList(taskList);
                        } else {
                            mTaskAdapter.addData(taskList);
                            if (taskList.isEmpty()) {
                                mPage--;
                            }
                        }
                    }
                    hideSkeleton();
                }, throwable -> {
                    throwable.printStackTrace();
                    if (mPage == 1) {
                        mRefreshLayout.finishRefresh();
                    } else {
                        mRefreshLayout.finishLoadMore(1000);
                    }
                    hideSkeleton();
                }));
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        TaskListBean taskListBean = mTaskAdapter.getItem(position);
        if (taskListBean.getTaskType() == 1) {// 课程
            Curriculum curriculum = new Curriculum();
            curriculum.setId(taskListBean.getBusinessId());
            curriculum.setSnapshotId(taskListBean.getBusinessId() + "");
            curriculum.setName(taskListBean.getName());
            curriculum.setCoverImage(taskListBean.getCoverImage());
            curriculum.setCourseUserId(taskListBean.getCourseUserId());
            CurriculumDetailsActivity.actionStart(getContext(), curriculum, CurriculumDetailsActivity.TYPE_FROM_TASK);
        } else if (taskListBean.getTaskType() == 2) {// 考试
        //    try {
//                Intent intent = new Intent(getActivity(), MyExamActivity.class);
//                intent.putExtra("data",taskListBean);
//                startActivity(intent);

            try {
                SharedPreferences settingss = getActivity().getSharedPreferences("tryToSwitch", 0);
                int isAmazing = settingss.getInt("tryToSwitch", 0);
                if (isAmazing == 2) {
                    //梁尔宾 原生去考试
                    Intent intent = new Intent(getActivity(), TheTestActivity.class);
                    intent.putExtra("examId", taskListBean.getBusinessId() + "");
                    intent.putExtra("relationshipId", "");
                    intent.putExtra("address", 1);
                    startActivity(intent);
                } else {
                    String token = URLEncoder.encode(BaseApplication.getContext().getToken(), "UTF-8");
                    String url = WebViewHelper.getBaseUrl() + "exam/examInfo?sourceId=" + taskListBean.getBusinessId() + "&fromType=1&token=" + token;
                    Log.e("MyWebViewActivity", "url: " + url);
                    MyWebViewActivity.actionStart(getContext(), url, "", 1);
                }



            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }



/*
                String token = URLEncoder.encode(BaseApplication.getContext().getToken(), "UTF-8");
                String url = WebViewHelper.getBaseUrl() + "exam/examInfo?sourceId=" + taskListBean.getBusinessId() + "&fromType=1&token=" + token;
                Log.e("MyWebViewActivity", "url: " + url);
                MyWebViewActivity.actionStart(getContext(), url, "", 1);


                mHasClickToNewPage = true;
/*            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }*/
        }
    }

    private static class TaskAdapter extends BaseQuickAdapter<TaskListBean, BaseViewHolder> {

        TaskAdapter(int layoutResId) {
            super(layoutResId);
        }

        @Override
        protected void convert(@NotNull BaseViewHolder baseViewHolder, TaskListBean task) {
            ImageView ivIcon = baseViewHolder.getView(R.id.iv_icon);
            if (CompatHelper.isEmpty(task.getCoverImage()) || task.getTaskType() == 2) {// 考试类别，没有图片
                ivIcon.setImageResource(R.drawable.ic_default_list_task);
            } else {
                ImageLoaderKt.loadImageSameCorners(ivIcon, task.getCoverImage(), 5f);
            }
            baseViewHolder.setText(R.id.tv_name, task.getName().trim())
                    .setText(R.id.tv_limit_time, new StringBuilder("截止：")
                            .append(CompatHelper.isEmpty(task.getEndTime()) ? "--" : CompatHelper.getDateString(task.getEndTime())));
            ImageView ivType = baseViewHolder.getView(R.id.iv_task_type);
            if (task.getTaskType() == 1) {
                ivType.setBackgroundResource(R.drawable.ic_task_type_course);
            } else if (task.getTaskType() == 2) {
                ivType.setBackgroundResource(R.drawable.ic_task_type_examination);
            }
        }
    }
}
